﻿using System;
using UnityEngine;

namespace Lockstep
{
    public class Energy: Ability
    {
        [SerializeField, FixedNumber]
        private long _maxEnergy = FixedMath.One * 100;
        [SerializeField, FixedNumber]
        private long _damageEnergyDelta = FixedMath.One * 10;
        public long BaseEnergy { get { return _maxEnergy; } }
        [SerializeField, FixedNumber]
        private long _currentEnergy = 0;
        public event Action onEnergyChange;
        private Health HealthComp;
        public long MaxEnergy
        {
            get { return _maxEnergy; }
        }
        public long EnergyAmount
        {
            get
            {
                return _currentEnergy;
            }
            set
            {
                long delta = value - _currentEnergy;
                _currentEnergy = value;
                if (onEnergyChange != null)
                    onEnergyChange();
            }

        }

        protected override void OnSetup()
        {
            HealthComp = Agent.GetAbility<Health>();
            HealthComp.onHealthDelta += OnHealthDelta;
        }

        private void OnHealthDelta(long delta)
        {
            var DoubleHealthDelta = Mathf.Abs(delta * 1.0f);
            var DoubleMaxHealth = HealthComp.MaxHealth * 1.0;
            var DeltaEnergyProportion = (DoubleHealthDelta / DoubleMaxHealth);
            var DeltaEnergy = MaxEnergy * DeltaEnergyProportion;
            EnergyAmount = EnergyAmount + (long)DeltaEnergy;
        }

        public void AddEnergyOnCausedDamage()
        {
            EnergyAmount = EnergyAmount + _damageEnergyDelta;
        }

        protected override void OnInitialize()
        {
            EnergyAmount = 0;
        }
    }
}
